#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
@File    :   update.py
@Time    :   2024-04-20 18:51
@Author  :   坐公交也用券
@Version :   1.0
@Contact :   faith01238@hotmail.com
@Homepage : https://liumou.site
@Desc    :   更新源
"""
import os


def chrony():
	txt = """# Use public servers from the pool.ntp.org project.
# Please consider joining the pool (http://www.pool.ntp.org/join.html).
pool ntp.tuna.tsinghua.edu.cn iburst

# Location of the file specifying the keys required for NTP authentication.
keyfile /etc/chrony/chrony.keys

# Specify the drift file.
driftfile /var/lib/chrony/chrony.drift

# Allow the system clock to be stepped in the first three updates
# if its offset is larger than 1 second.
makestep 1 3

# Enable kernel synchronization of the real-time clock (RTC).
rtcsync

# Specify directory for log files.
logdir /var/log/chrony

# Specify directory for dumping Network Time Security (NTS) data.
ntsdumpdir /var/lib/chrony


# Enable hardware timestamping if available.
# hwtimestamp *

# Prevent clock updates larger than 0.5 seconds, unless first synchronizing.
maxslewrate 500

# Use the hardware clock as a reference.
# refclock PHC /dev/ptp0 poll 3 dpoll -2 offset 0

# Specify the NTP server pool file.
#server 0.centos.pool.ntp.org iburst
#server 1.centos.pool.ntp.org iburst
#server 2.centos.pool.ntp.org iburst
#server 3.centos.pool.ntp.org iburst

# Specify additional NTP servers.
#server ntp.mydomain.com

# Specify additional NTP peers.
#peer ntp.mypeer.com

# Allow NTP clients to access this server.
allow all

# Specify the command key.
#commandkey 1

# Specify the command ACL.
#cmdallow 192.0.2.0/24
#cmddeny 192.0.2.200

# Enable access control logging.
#logchange 0.5
"""
	return txt


class UpdateSource:
	def __init__(self):
		self.url = 'https://mirrors.tuna.tsinghua.edu.cn'

	def set_time(self):
		"""
		设置时间
		:return:
		"""
		try:
			with open(file="/etc/chrony/chrony.conf", mode='w+', encoding='utf8') as w:
				w.write(chrony())
		except Exception as e:
			print(e)
		print("正在设置时间")
		os.system("timedatectl set-timezone Asia/Shanghai")
		os.system("timedatectl set-ntp true")
		os.system("systemctl daemon-reload")
		if os.system("systemctl restart chrony") != 0:
			print("时间同步服务启动失败")
			return
		if os.system("chronyc makestep") != 0:
			print("时间手动同步失败")
			return
		print("设置时间成功")

	def write(self, file, txt):
		"""
		写入配置
		:param file: 文件对象
		:param txt: 内容
		:return:
		"""
		print(f"正在写入配置: {file}")
		print(txt)
		try:
			with open(file=file, mode='w', encoding='utf8') as w:
				w.write(txt)
		except Exception as e:
			print(f"无法写入配置: {e}")
			return
		print("写入配置成功")

	def update_os(self):
		"""
		更新系统源
		:return: 
		"""
		txt = f"""# 默认注释了源码镜像以提高 apt update 速度，如有需要可自行取消注释
deb {self.url}/debian/ bookworm main contrib non-free non-free-firmware
# deb-src {self.url}/debian/ bookworm main contrib non-free non-free-firmware

deb {self.url}/debian/ bookworm-updates main contrib non-free non-free-firmware
# deb-src {self.url}/debian/ bookworm-updates main contrib non-free non-free-firmware

deb {self.url}/debian/ bookworm-backports main contrib non-free non-free-firmware
# deb-src {self.url}/debian/ bookworm-backports main contrib non-free non-free-firmware

deb {self.url}/debian-security bookworm-security main contrib non-free non-free-firmware
# deb-src {self.url}/debian-security bookworm-security main contrib non-free non-free-firmware
"""
		self.write(file='/etc/apt/sources.list', txt=txt)

	def update_ceph(self):
		"""
		更新ceph源
		:return:
		"""
		txt = f"""deb {self.url}/ceph/debian-quincy bookworm enterprise"""
		self.write(file='/etc/apt/sources.list.d/ceph.list', txt=txt)

	def update_proxmox(self):
		"""

		:return:
		"""
		txt = f'deb {self.url}/proxmox/debian/pve bookworm pve-no-subscription'
		self.write(file='/etc/apt/sources.list.d/pve-enterprise.list', txt=txt)

	def select(self):
		"""
		选择更新源
		:return:
		"""
		print("请选择源加速站点:")
		print("1. 清华大学(推荐)")
		print("2. 腾讯云(未测试)")
		print("3. 阿里云(未测试)")
		while True:
			try:
				num = int(input("请输入数字: \n"))
				if num == 1:
					self.url = 'https://mirrors.tuna.tsinghua.edu.cn'
					break
				elif num == 2:
					self.url = 'https://mirrors.cloud.tencent.com'
					break
				elif num == 3:
					self.url = 'https://mirrors.aliyun.com'
				else:
					print("输入错误")
			except Exception as e:
				print(f"只能输入整数: {e}")

	def update_index(self):
		"""
		更新源索引
		:return:
		"""
		print("正在更新源索引...")
		os.system("apt update")

	def update_ct(self):
		"""
		更新ct源
		:return:
		"""
		src = "/usr/share/perl5/PVE/APLInfo.pm"
		dst = "/usr/share/perl5/PVE/APLInfo.pm_back"
		print("正在更新ct源...")
		if not os.path.exists(dst):
			if os.system(f"cp {src} {dst}") != 0:
				print(f"无法备份: {src}")
				return
		if os.system(
				f"sed -i 's|http://download.proxmox.com|https://mirrors.tuna.tsinghua.edu.cn/proxmox|g' {src}") != 0:
			print(f"无法更新配置: {src}")
			return
		print("CT源加速配置完成,重启后生效")

	def start(self):
		self.select()
		self.set_time()
		self.update_os()
		self.update_ceph()
		self.update_proxmox()
		self.update_index()
		self.update_ct()


if __name__ == '__main__':
	up = UpdateSource()
	up.start()
